define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'store/purcha/index',
                    add_url: 'store/purcha/add',
                    table: 'purcha',
                    import_url: 'store/purcha/import'

                }
            });

            var table = $("#table");
            $(".dels").on("click",function () {
                alert(123123)
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'order_id', title:'订单号'},

                        {field: 'supplier', title: '供应商'},
                        {field: 'other_money', title: __('Other_money'), operate:false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'publisher', title: __('Publisher')},
                        {field: 'mark', title: __('Mark')},
                        {field: 'status', title: __('Status'), searchList: {"1":'已入库',"2":'部分入库',"3":'待入库',"4":'作废'}, formatter: Table.api.formatter.status},

                        {
                            field: 'name',

                            title: __('操作'),
                            table: table,
                            events: Controller.api.events.voids,
                            buttons: [],
                            formatter: Controller.api.formatter.voids
                        },

                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

        },
        add: function () {

            var index = $("#ultable").attr("data-listidx");
            layer.load("加载中");
            setTimeout(function() {//异步处理，防止冒泡事件，select未加载成功
                layer.closeAll();
                $(".btn-append").click(function () {

                    var str='<tr id="tr'+index+'"><td>1</td><td ><input  data-id="'+index+'"  data-rule="required"  style="width:280px" id="sele'+index+'" data-source="ajax/shop"  data-field="cname" data-primary-key="id" name="shop['+index+'][id]"  class="form-control selectpage wuji" style="width:100%" placeholder="请选择商品"  type="text" value="" autocomplete="off"></td>';

                    str+='<td id="bh'+index+'">&nbsp;</td><td id="fl'+index+'">&nbsp;</td><td id="sl'+index+'">&nbsp;</td><td id="dj'+index+'">&nbsp;</td><td id="xj'+index+'">&nbsp;</td><td id="sc'+index+'"><a data-id="'+index+'" style="cursor: pointer" class="del btn btn-xs btn-success btn-editone"><i class="fa fa-trash"></i></a></td>';
                    str+='</tr>';


                    $("#ultable").append(str);
                    $("#sele"+index).selectPage({
                        params:{'rows':index},
                        eAjaxSuccess: function (data) {
                            data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                            data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                            return data;
                        },
                        dropButton : false,

                        eSelect : function(data) {

                            var ind = this.params.rows;//当前行数
                            /* var wuji = $('.wuji');
                             if (wuji.length > 1) {
                                 var j = 0;//查看当前值出现的次数，如果 》 1则重复了。
                                 for (var i = 0; i < wuji.length; i++) {
                                     var did = wuji.eq(i).data('id');
                                     if ($("#sele" + did).val() == data.id) {
                                         j++;
                                     }
                                 }
                                 if (j > 1) {
                                     layer.alert("不能重复选择" + data.cname);
                                     $("#sele" + ind).selectPageClear();
                                     return;
                                 }
                             }
                             var dselects = $("#ultable").attr("data-selects");
                             if (dselects == '') {
                                 $("#ultable").attr("data-selects", data.id);
                             } else {

                                $("#ultable").attr("data-selects", dselects + ',' + data.id);
                             }*/
                            // $("#sele"+ind).selectPageClear();
                            $("#bh"+ind).html(data.b_n);
                            $("#fl"+ind).html(data.className);
                            $("#sl"+ind).html('<input type="text"  data-rule="required"  autocomplete="off" value="1" placeholder="1" class="form-control form-num zzwselect" name="shop['+ind+'][num]"> ');
                            $("#dj"+ind).html('<input type="text"  data-rule="required"  autocomplete="off" value="100" placeholder="100" class="form-control form-price" name="shop['+ind+'][price]"> ');
                            $("#xj"+ind).html('100.00');
                            $("#sl"+ind).find('input').focus();
                            plus();
                        }







                    });

                    table_sort();
                    index++;
                });
            },500);
            $("#ultable").on("click",".del",function(){
                var ind = $(this).attr('data-id');
                $("#sele"+ind).selectPageClear();
                $("#tr"+ind).remove();
                table_sort();
            });

            $("#ultable").on("keyup",".form-num",function(){
                plus();
            });
            $("#ultable").on("keyup",".form-price",function(){
                plus();
            });
            $("#ultable").on("blur",".form-num",function(){
                $(this).parent('td').next('td').find('input').focus();
                plus();
            });
            $("#ultable").on("blur",".form-price",function(){
                plus();
            });
            function plus() {
                var nums = $('.form-num');
                var price = $('.form-price');

                //计算总数量
                var jn=0;
                var jp=0;
                for (var i=0;i<nums.length;i++){
                    jn+=parseInt(nums.eq(i).val());
                    var p = parseFloat(price.eq(i).val())==NaN ? 0 : parseFloat(price.eq(i).val());
                    jp+=parseFloat(p*parseInt(nums.eq(i).val()));
                    nums.eq(i).parent('td').next().next().html(parseFloat(p*parseInt(nums.eq(i).val())));
                }
                $("#tj1").html(jn);

                $("#tj2").html(parseFloat(jp).toFixed(2));

            }

            //前面数字排序
            function table_sort() {
                var trs = $("#ultable tr");
                if (trs.length==0)return;
                for (var i=1;i<=trs.length;i++){
                    trs.eq(i-1).find('td').eq(0).html(i);
                }


            }




            Controller.api.bindevent();
        },
        view:function(){

            $("#ruku").click(function () {
                var that = $(this);
                if (that.hasClass('disabled')) return false;
                var r=confirm("确定入库吗？");
                if (r==true){
                    var str='';
                    var pur_id = $(this).attr("data-id")//采购单id

                    $(".list-qd").each(function (e,v) {
                        str+=$(this).attr("shopid")+"|"+$(this).val()+","
                    })

                    $.ajax({
                        url:"/admin/store/purcha/ruku",
                        type:"post",
                        data:{pur_id:pur_id,str:str},
                        beforeSend:function() {
                            that.addClass("disabled");
                            that.html("入库中...");

                            layer.load();
                        },
                        success:function (data) {
                            if(data.code==1){
                                //成功
                                layer.closeAll();

                                layer.msg("入库成功");
                                setTimeout(function () {
                                    location.reload();
                                },2000)

                            }else{
                                layer.msg(data.msg);
                                layer.closeAll();
                                that.removeClass("disabled");

                            }
                        }
                    })
                }


                // location.reload()
                /*  */

            });

            Controller.api.bindevent();

        },

        retreat:function(){


            Controller.api.bindevent();

        },
        ware:function(){


            Controller.api.bindevent();

        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            events:{
                voids:{
                    'click .btn-voids': function (e, value, row, index) {
                        e.stopPropagation();
                        e.preventDefault();
                        var that = this;
                        var top = $(that).offset().top - $(window).scrollTop();
                        var left = $(that).offset().left - $(window).scrollLeft() - 260;
                        if (top + 154 > $(window).height()) {
                            top = top - 154;
                        }
                        if ($(window).width() < 480) {
                            top = left = undefined;
                        }
                        Layer.confirm(
                           "确定作废此采购单吗",
                            {icon: 3, title: __('Warning'), offset: [top, left], shadeClose: true},
                            function (index) {
                                var options = {url: "store/purcha/voids/ids/1"};

                                Fast.api.ajax(options,function (data,ret) {

                                  $(".btn-refresh").trigger("click");

                                });
                                Layer.close(index);

                            }
                        );
                    },

                }
            },
            formatter:{
                voids: function (value, row, index) {
                    var table = this.table;
                    // 默认按钮组
                    var buttons = [];
                    if (row.status == 4) {
                        buttons.push({
                            name: '已作废',
                            title: "已作废",
                            text: "已作废",
                            extend: 'data-toggle="tooltip"',
                            classname: 'btn btn-xs',
                        });
                    } else {

                        buttons.push({
                            name: '作废',
                            title: "作废",
                            text: "作废",
                            extend: 'data-toggle="tooltip"',
                            classname: 'btn btn-xs btn-voids',
                        });
                      }
                    buttons.push({
                        name: '查看订单',
                        title: "查看订单",
                        text: "查看订单",
                        url:'store/purcha/view',
                        extend: 'data-toggle="tooltip"',
                        classname: 'btn btn-xs btn-dialog',
                    });
                    return Table.api.buttonlink(this, buttons, value, row, index, 'buttons');
                }
            }

        }
    }
    return Controller;
});
